<template>
  <div class="address-edit-box">
    <s-header :name="`${state.type == 'add' ? '新增地址' : '编辑地址'}`"></s-header>
    <div class="map-container">
      <input id="searchInput" ref="searchInputRef" />
      <div id="map" style="width: 100%; height: 300px;"></div>
    </div>
    <van-address-edit ref="addressEditRef" class="edit" :area-list="areaData" :address-info="addressInfo"
      :show-delete="state.type == 'edit'" show-set-default show-search-result :search-result="state.searchResult"
      @save="onSave" @delete="onDelete" />
  </div>
</template>

<script lang="ts" setup>
import { reactive, onMounted, ref, nextTick, onUnmounted, computed } from 'vue'
import { type AddressEditInfo, showToast } from 'vant'
import sHeader from '@/components/SimpleHeader.vue'
import { useRoute, useRouter } from 'vue-router'
// import { useAuthInfoHook } from "@/utils/request";
import { Address, useAddress } from "@/stores/address";
import { useArea } from '@/common/js/area';
const route = useRoute()
const router = useRouter()

//#region 省市县数据
const {
  provinceList,
  allCityList,
  allAreaList,
  getAreaId,
} = useArea()
const areaData = computed(() => {
  const province_list: any = {}
  const city_list: any = {}
  const county_list: any = {}
  provinceList.value.forEach(item => {
    province_list[item.id] = item.name
  })
  allCityList.value.forEach(item => {
    city_list[item.id] = item.name
  })
  allAreaList.value.forEach(item => {
    county_list[item.id] = item.name
  })
  return {
    province_list,
    city_list,
    county_list,
  }
})
//#endregion

const { getAddress, getAddressList, address, addOrUpdateAddress, deleteAddress } = useAddress()

const addrId = ref('')
const addressInfo = ref<AddressEditInfo>({
  tel: '',
  name: '',
  city: '',
  county: '',
  country: '',
  province: '',
  areaCode: '',
  isDefault: false,
  addressDetail: '',
})

const state = reactive<any>({
  searchResult: [],
  type: 'add',
})

const addressEditRef = ref()

onMounted(async () => {
  await getAddressList()
  const { addressId, type } = route.query
  state.type = type
  if (type == 'edit') {
    //@ts-ignore
    const data: Address = getAddress(addressId)
    addrId.value = data.id || ''
    addressInfo.value = {
      tel: data.phone,
      name: data.name,
      city: data.city,
      county: data.area,
      country: '',
      province: data.province,
      areaCode: '',
      isDefault: address.defaultId === addressId,
      addressDetail: data.addr,
    }
    // 数据回显
    const areaId = getAreaId(data.area, data.city, data.province)
    addressEditRef.value?.setAreaCode(areaId)
  }
  initBmap()
  nextTick(() => {
    initLocalSearch()
  })
})
onUnmounted(() => {
  map.value = null
  autoComplete.value = null
})
const map = ref<any>()
const autoComplete = ref<any>()
const searchInputRef = ref()
const initBmap = () => {
  // 创建地图实例
  //@ts-ignore
  map.value = new BMap.Map('map');
  //@ts-ignore
  const point = new BMap.Point(116.404, 39.915); // 默认中心点
  map.value.centerAndZoom(point, 11);
  map.value.enableScrollWheelZoom(true); // 开启鼠标滚轮缩放
  //@ts-ignore
  autoComplete.value = new BMap.Autocomplete({
    input: searchInputRef.value,
    location: map.value,
  })
  autoComplete.value.addEventListener("onconfirm", (e: any) => {
    let { province, business, city, district, street, streetNumber } = e.item.value
    console.log(province, city, district, streetNumber, e)
    if (!province && !city) {
      showToast({
        message: '该地址百度识别无效，请重新输入',
        duration: 3000,
      })
      return
    }
    if (province === city) province = ''
    const area = district
    const addr = street + streetNumber + business
    console.log(addr)
    const areaId = getAreaId(area, city, province)

    addressInfo.value.province = province
    addressInfo.value.city = city
    addressInfo.value.county = area
    nextTick(() => {
      addressEditRef.value?.setAreaCode(areaId)
      addressEditRef.value?.setAddressDetail(addr)
    })
  })
}
const localSearch = ref<any>()
const initLocalSearch = () => {
  //@ts-ignore
  localSearch.value = new BMap.LocalSearch(map.value, {
    renderOptions: {
      map: map.value,
    }
  });
  localSearch.value.setPageCapacity(10); // 设置每页显示的结果条数
};

const geocoder = ref()
const getLocation = (address: string) => {
  // @ts-ignore
  geocoder.value = geocoder.value || new BMap.Geocoder()
  return new Promise((resolve, reject) => {
    geocoder.value.getPoint(address, (point: any) => {
      if (point) {
        resolve(point)
      } else {
        reject('未能获取经纬度')
      }
    })
  })
}
const loading = ref<boolean>(false)
const onSave = async (content) => {
  if(loading.value) return
  loading.value = true
  const {
    addressDetail,
    county,
    city,
    isDefault,
    name,
    province,
    tel } = content

  try {
    const point: any = await getLocation(`${province}${city}${county}${addressDetail}`)
    console.log(point)
    const params = {
      id: addrId.value?Number(addrId.value):undefined,
      name: name,
      phone: tel,
      province: province,
      cityName: city,
      area: county,
      addr: addressDetail,
      lat: point.lat,
      lng: point.lng,
      isDefault
    }
    await addOrUpdateAddress(params)
  } catch (e) {
    console.log(e)
  } finally {
    setTimeout(() => {
      loading.value = false
    }, 1000)
  }
  showToast('保存成功')
  setTimeout(() => {
    router.back()
  }, 1000)
}

const onDelete = async () => {
  await deleteAddress(addrId.value)
  showToast('删除成功')
  setTimeout(() => {
    router.back()
  }, 1000)
}
</script>

<style lang="less">
@import '../common/style/mixin';

.edit {
  .van-field__body {
    textarea {
      height: 26px !important;
    }
  }
}

.address-edit-box {
  --van-button-primary-background: @primary;
  --van-button-border-width: 0;

  .van-address-edit {
    .van-button--danger {
      background: @primary;
      border-color: @primary;
    }

    .van-switch--on {
      background: @primary;
    }
  }
}

#searchInput {
  outline: 1px solid #ddd;
  position: absolute;
  top: 10px;
  width: 90%;
  left: 5%;
  border-radius: 6px;
  padding: 6px 12px;
  z-index: 999;

  &:hover {
    outline: none;
    box-shadow: #999 0 0 8px 1px;
  }
}
</style>
